import React, { useState, useEffect, useImperativeHandle, forwardRef } from "react"
import {
    Icon,
    Space,
    Popover,
    Input,
    Button,
    Tag,
    Modal,
    message,
    Divider,
    Form
} from "@bytedance/mona-ui"
import { shuffleArray } from './copyDataFomate'
import './title.scss'
import { useAppDispatch } from "~store"
import {
    setJiebaTitle
} from "~store/controller/jinritemaiCopyGoods"
import {
    getMiniTitle
} from "@Api/productApi"

const { TextArea } = Input
// import moment from 'moment'
function getStrLen(str) {
    var charsToReplace = ["～", '！', '¥', '（', '）', '【', '】', '「', '」'];

    // 将数组元素用管道符(|)连接，创建一个正则表达式
    var regex = new RegExp(charsToReplace.join('|'), 'g');

    return str.replace(regex, 'a').replace(/[^\x00-\xff]/g, "aa").length
}

// function getMiniTitleFunc() {

// }

const TitleJieba = (props, ref) => {
    const { titleJfrStart, copyGoodConfig, titleLimitRule, searchWord, goodsDetellData } = props
    if (!titleJfrStart) return null
    if (!titleLimitRule) return null
    const { max_length, min_length } = titleLimitRule
    const { cuts } = titleJfrStart
    const { copynum } = copyGoodConfig
    const dispacth = useAppDispatch()
    let isAddList: number[] = []
    let addContent: string[] = []
    // const { copynum } = copyGoodConfig
    function addTitleDataAi() {
        isAddList = []
        addContent = []
        if (!searchWord || searchWord.length < 20) {
            return { title: '', cuts: [] }
        }
        const getader = getTitleRefoter()
        return { title: getader.join(''), cuts: getader }

    }
    function getTitleRefoter() {
        // console.log('searchWord', searchWord)
        if (!searchWord || searchWord.length < 20) {
            return []
        }
        // return []

        const miyer: number = Math.floor(Math.random() * searchWord.length)
        if (!isAddList.includes(miyer)) {
            const strs = searchWord[miyer].cell_info?.query.query_value.value.value_str
            let interCount = strs.replace(/[^\x00-\xff]/g, "aa").length
            let interlength = addContent.join('').replace(/[^\x00-\xff]/g, "aa").length
            let outInterlength = max_length - interlength
            if (outInterlength >= interCount) {
                addContent.push(searchWord[miyer].cell_info.query.query_value.value.value_str)
                isAddList.push(miyer)
                getTitleRefoter()
            }
        } else {
            getTitleRefoter()
        }
        return addContent
    }
    function getTitleListAi() {
        let titleListCOntent: any[] = []
        for (let i = 0; i < copynum; i++) {
            const getader = addTitleDataAi()
            titleListCOntent.push(getader)
        }
        return titleListCOntent
    }

    const [refoConterDataAi, setRefoConterDataAi] = useState<any[]>(searchWord && searchWord.length && getTitleListAi())
    // console.log('refoConterDataAi', refoConterDataAi)
    function addTitleData() {
        const shuff = JSON.parse(JSON.stringify(cuts)) //shuffleArray(cuts)
        let titleCopyData = {
            title: (() => {
                let ti = ''
                shuff.forEach((item, index) => {
                    ti += item
                })
                return ti
            })(),
            cuts: JSON.parse(JSON.stringify(shuff)),
            miniTitle: goodsDetellData.short_product_name
        }
        return titleCopyData
    }
    function getTitleList() {
        const titleList: any = []
        for (let i = 0; i < copynum; i++) {
            titleList.push(addTitleData())
        }
        return titleList
    }

    const [refoConterData, setRefoConterData] = useState<any[]>(getTitleList())
    // useEffect(() => {
    //     dispacth(setJiebaTitle(JSON.parse(JSON.stringify(refoConterData))))
    // }, [refoConterData])
    useImperativeHandle(ref, () => ({
        refoConterData
    }));
    useEffect(() => {
        // const chegr = moment().startOf('day').subtract(1, 'days').subtract(1,'months').format('YYYY/MM/DD HH:mm:ss')
        // console.log('err', chegr)

        if (refoConterData.length === copynum) {
            return
        }
        const addConter = copynum - refoConterData.length
        if (addConter > 0) {
            for (let i = 0; i < addConter; i++) {
                refoConterData.push(addTitleData())
                refoConterDataAi && refoConterDataAi.length && refoConterDataAi.push(addTitleDataAi())
            }
        } else {
            refoConterData.splice(addConter, Math.abs(addConter))
            refoConterDataAi && refoConterDataAi.length && refoConterDataAi.splice(addConter, Math.abs(addConter))
        }
        refoConterDataAi && refoConterDataAi.length && setRefoConterDataAi([...refoConterDataAi])
        setRefoConterData([...refoConterData])
    }, [copynum])
    let movingDom
    const [addValue, setAddValue] = useState('')
    const [addTitleAll, setAddTitleAll] = useState(false)
    const [addTitleAllText, setAddTitleAllText] = useState('')

    useEffect(() => {
        console.log('refoConterData', refoConterData)
    }, [refoConterData])
    return (
        <div style={{
            marginLeft: 25
        }}>
            <div className="lterconter">
                <Space direction="vertical">
                    <div className="sye" style={{
                        color: '#000',
                        fontSize: 14,
                        fontWeight: 900,
                    }}>
                        批量调整

                    </div>
                    <Space>

                        <Button type="link" icon={<Icon type="RefreshIcon" />} onClick={(e) => {
                            // console.log('eee添加')
                            // isAddList = []
                            // addContent = []
                            // const refodater = getTitleRefoter()
                            // console.log('refodater', refodater)
                            // console.log('refoConterData', refoConterData)
                            refoConterData.forEach((item, index) => {
                                item.cuts = shuffleArray(item.cuts)
                                item.title = ''
                                item.cuts.forEach((conter, conindex) => {
                                    item.title += conter
                                })
                            })
                            // refoConterDataAi[index].cuts = refodater
                            setRefoConterData([...refoConterData])
                        }}>重新排序全部标题</Button>
                        <Button type="link" style={{
                            color: "red"
                        }} icon={<Icon type="DeleteIcon" />} onClick={(e) => {
                            // console.log('eee添加')
                            // isAddList = []
                            // addContent = []
                            // const refodater = getTitleRefoter()
                            // console.log('refodater', refodater)
                            // console.log('refoConterData', refoConterData)
                            refoConterData.forEach((item, index) => {
                                item.cuts = []
                                item.title = ''

                            })
                            // refoConterDataAi[index].cuts = refodater
                            setRefoConterData([...refoConterData])
                        }}>删除全部标题</Button>
                        <Button type="link" icon={<Icon type="AddIcon" />} onClick={(e) => {
                            setAddTitleAll(true)
                        }}>批量添加标题</Button>
                    </Space>
                    <Space>
                        <Button size="mini" onClick={() => {
                            console.log('导购短标题')
                            refoConterData.forEach((item, index) => {
                                const getData = {
                                    "context": {
                                        "ability": [],
                                        "biz_identity": "xiaodian",
                                        "category_id": goodsDetellData.category_leaf_id_gt + ''
                                    },
                                    "model": {
                                        "title": {
                                            "value": shuffleArray(JSON.parse(JSON.stringify(item.cuts))).join('')
                                        }
                                    }

                                }
                                getMiniTitle(getData).then(res => {
                                    console.log('getReadTitleData', res)
                                    if (!res.code) {
                                        item.miniTitle = res.data?.model?.short_product_name.value
                                        setRefoConterData([...refoConterData])
                                    }
                                })

                            })
                            // refoConterDataAi[index].cuts = refodater
                            // setRefoConterData([...refoConterData])
                        }}>批量智能生成导购短标题</Button>
                    </Space>
                </Space>
            </div>
            {/* <div className="titlebox"></div> */}

            {refoConterData.map((item, index) => {
                return (<div className="lterconter" key={index}>
                    <Space direction="vertical">
                        <div className="titlebox">
                            <Space>
                                <Button type="link" icon={<Icon type="RefreshIcon" />} onClick={(e) => {
                                    item.cuts = shuffleArray(item.cuts)
                                    item.title = ''
                                    item.cuts.forEach((conter, conindex) => {
                                        item.title += conter
                                    })
                                    setRefoConterData([...refoConterData])
                                }}></Button>
                                {/* <Icon type="RetryIcon"
                                style={{
                                    color: '#565960',
                                    cursor: 'pointer',
                                    marginRight: 5,
                                    // display: (getStrLen(item.title) > 60 || getStrLen(item.title) < 15) ? 'block' : 'none'
                                }}
                                onClick={() => {
                                    

                                }}
                            ></Icon> */}
                                标题{index + 1}(<span className="cine" style={{
                                    color: (getStrLen(item.title) > max_length || getStrLen(item.title) < min_length) ? 'red' : '#565960'
                                }}>
                                    {getStrLen(item.title)} / {max_length}
                                </span>):<span> {item.title}</span>
                                <Button style={{
                                    color: 'red'
                                }} type="link" icon={<Icon type="DeleteIcon" ></Icon>} onClick={() => {
                                    // refoConterData.splice(index, 1)
                                    item.cuts = []
                                    item.title = ''
                                    setRefoConterData([...refoConterData])
                                    // setRefoConterData([...refoConterData])
                                }}>删除标题</Button>

                            </Space>

                        </div>
                        <div className="boter teurdaonter" style={{
                            borderColor: (getStrLen(item.title) > { max_length } || getStrLen(item.title) < min_length) ? 'red' : '#f0f0f0'
                        }}>
                            {item.cuts.map((conter, conindex) => {
                                return (
                                    <div
                                        draggable
                                        className="tagconter"
                                        key={conindex + conter}
                                        data-index={conindex}
                                        onDragStart={(e: any) => {
                                            setTimeout(_ => {
                                                e.target.classList.add('moving')
                                            })
                                            movingDom = e.target
                                            e.dataTransfer.effectAllowed = 'move'
                                        }}
                                        onDragEnd={(e: any) => {
                                            e.preventDefault()
                                            e.target.classList.remove('moving')
                                            item.title = ''
                                            item.cuts = []
                                            setTimeout(_ => {
                                                movingDom.parentNode.childNodes.forEach((itemtit, index) => {
                                                    item.title += itemtit.innerText
                                                    console.log('itemtit.innerText', itemtit.innerText)
                                                    itemtit.innerText && item.cuts.push(itemtit.innerText)
                                                })
                                                setRefoConterData([...refoConterData])
                                            }, 200)

                                            console.log('停止移动')
                                        }}
                                        onDragOver={(e) => {
                                            e.preventDefault()
                                            console.log('结束的时机')
                                        }}
                                        onDragEnter={(e: any) => {
                                            e.preventDefault()
                                            if (e.target === movingDom || e.target === movingDom.parentNode || e.target.parentNode !== movingDom.parentNode) {
                                                return
                                            }
                                            if (e.target.classList.contains('tagconter')) {
                                                const chlist = Array.from(movingDom.parentNode.childNodes)
                                                const movingIndex = chlist.indexOf(movingDom)
                                                const targetIndex = chlist.indexOf(e.target)
                                                if (movingIndex > targetIndex) {
                                                    movingDom.parentNode.insertBefore(movingDom, e.target)
                                                } else {
                                                    movingDom.parentNode.insertBefore(movingDom, e.target.nextElementSibling)
                                                }
                                            }
                                        }}
                                    >
                                        <span className="coneyr">
                                            <svg width="6" height="10" viewBox="0 0 6 10" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path fill-rule="evenodd" clip-rule="evenodd" d="M1 0C0.447715 0 0 0.447715 0 1C0 1.55228 0.447715 2 1 2C1.55228 2 2 1.55228 2 1C2 0.447715 1.55228 0 1 0ZM5 0C4.44772 0 4 0.447715 4 1C4 1.55228 4.44772 2 5 2C5.55229 2 6 1.55228 6 1C6 0.447715 5.55229 0 5 0ZM0 5C0 4.44772 0.447715 4 1 4C1.55228 4 2 4.44772 2 5C2 5.55229 1.55228 6 1 6C0.447715 6 0 5.55229 0 5ZM5 4C4.44772 4 4 4.44772 4 5C4 5.55229 4.44772 6 5 6C5.55229 6 6 5.55229 6 5C6 4.44772 5.55229 4 5 4ZM0 9C0 8.44772 0.447715 8 1 8C1.55228 8 2 8.44772 2 9C2 9.55229 1.55228 10 1 10C0.447715 10 0 9.55229 0 9ZM5 8C4.44772 8 4 8.44772 4 9C4 9.55229 4.44772 10 5 10C5.55229 10 6 9.55229 6 9C6 8.44772 5.55229 8 5 8Z" fill="#898B8F" />
                                            </svg>
                                        </span>
                                        <span className="timer itecnayer" >
                                            {conter}
                                        </span>
                                        <Icon
                                            type="CloseIcon"
                                            style={{
                                                cursor: 'pointer',
                                            }}
                                            onClick={(e: any) => {
                                                const getTitle = document.querySelectorAll('.teurdaonter')
                                                const nouer: any = getTitle[index].querySelectorAll('.itecnayer')
                                                item.cuts = []
                                                nouer.forEach((itemtit: any, index) => {
                                                    item.cuts.push(itemtit.innerText)
                                                })

                                                item.cuts.splice(conindex, 1)
                                                item.title = ''
                                                item.cuts.forEach((items) => {
                                                    item.title += items
                                                })
                                                setRefoConterData([...refoConterData])
                                            }}
                                        ></Icon>
                                    </div>
                                )

                                //  <Tag key={conindex} color="primary" style={{
                                //     marginRight: 10,
                                // }}>{conter}</Tag>

                            })}
                            <Popover
                                className="conetrss"
                                trigger="click"
                                content={
                                    <Space direction="vertical">
                                        <Input
                                            size="small"
                                            placeholder="请输入"
                                            style={{
                                                width: '150px',
                                            }}
                                            className="inouterdater"
                                            value={addValue}
                                            onChange={(e: any) => {
                                                setAddValue(e.target.value)
                                            }}

                                        ></Input>
                                        <Space >
                                            <Button type="primary"
                                                size="small"
                                                onClick={(e: any) => {
                                                    item.cuts.push(addValue)

                                                    setRefoConterData([...refoConterData])
                                                    setTimeout(_ => {
                                                        const getTitle: any = document.querySelectorAll('.teurdaonter')

                                                        const nouer = getTitle[index].querySelectorAll('.itecnayer')

                                                        item.title = ''
                                                        nouer.forEach((itemtit: any, index) => {

                                                            item.title += itemtit.innerText
                                                        })
                                                        setRefoConterData([...refoConterData])
                                                        getTitle[index].querySelector('.conetrss').click()
                                                    })
                                                    setAddValue('')
                                                }}>确定</Button>
                                            <Button
                                                size="small"
                                                onClick={(e) => {
                                                    setAddValue('')
                                                    const getTitle: any = document.querySelectorAll('.teurdaonter')
                                                    getTitle[index].querySelector('.conetrss').click()
                                                }}>取消</Button>
                                        </Space>
                                    </Space>
                                }
                            >
                                <div className="tagconter">
                                    <Icon
                                        type="AddIcon"
                                        style={{
                                            cursor: 'pointer',
                                        }}
                                        onClick={(e: any) => {
                                            console.log('eee添加')
                                        }}
                                    ></Icon>
                                </div>
                            </Popover>
                        </div>
                        {refoConterDataAi[index] && refoConterDataAi[index].cuts && (refoConterDataAi[index].cuts.length !== 0) && <div className="mobotonctse">

                            <Space wrap>
                                <div>
                                    <Button type="link" icon={<Icon type="RefreshIcon" />} onClick={(e) => {
                                        console.log('eee添加')
                                        isAddList = []
                                        addContent = []
                                        const refodater = getTitleRefoter()
                                        console.log('refodater', refodater)
                                        refoConterDataAi[index].cuts = refodater
                                        setRefoConterData([...refoConterData])
                                    }}>刷新</Button>  <Tag color="#000" type="success">
                                        热搜词
                                    </Tag>
                                </div>
                                {refoConterDataAi[index].cuts.map((titel, keys) => {
                                    return <Tag bordered type="default" key={keys} style={{
                                        cursor: 'pointer',
                                    }}>
                                        <span onClick={() => {
                                            console.log('title', titel)
                                            item.cuts.push(titel)

                                            setRefoConterData([...refoConterData])
                                            setTimeout(_ => {
                                                const getTitle: any = document.querySelectorAll('.teurdaonter')

                                                const nouer = getTitle[index].querySelectorAll('.itecnayer')

                                                item.title = ''
                                                nouer.forEach((itemtit: any, index) => {

                                                    item.title += itemtit.innerText
                                                })
                                                setRefoConterData([...refoConterData])
                                                // getTitle[index].querySelector('.conetrss').click()
                                            })
                                        }}>
                                            {titel}
                                        </span>
                                    </Tag>
                                })}
                                {/* <div className="aiTitle">10231</div> */}
                            </Space>
                        </div>}

                        {getStrLen(item.title) > { max_length } && (
                            <div className="ciner" style={{
                                color: 'red',
                                fontSize: '12px',
                                // marginTop: '5px',
                            }}>最长不能超过{max_length}个字符</div>
                        )}
                        {getStrLen(item.title) < min_length && (
                            <div className="ciner" style={{
                                color: 'red',
                                fontSize: '12px',
                                // marginTop: '5px',
                            }}>最短不能少于{min_length}个字符</div>
                        )}
                        <Divider style={{
                            margin: '4px 0'
                        }}></Divider>
                        <Space>
                            <span>导购短标题 {index + 1}：</span>
                            <Form.Item noStyle>
                                <Input placeholder="请输入导购短标题" value={item.miniTitle} size="small" style={{
                                    width: 300
                                }}
                                    limit={24}
                                    calcLength={(str) => {
                                        return getStrLen(str)
                                    }}
                                    onChange={(e) => {
                                        item.miniTitle = e.target.value
                                        setRefoConterData([...refoConterData])
                                    }}
                                ></Input>
                            </Form.Item>
                            <Button type="link" onClick={(e) => {
                                console.log('智能导购短标题')
                                const getData = {
                                    "context": {
                                        "ability": [],
                                        "biz_identity": "xiaodian",
                                        "category_id": goodsDetellData.category_leaf_id_gt + ''
                                    },
                                    "model": {
                                        "title": {
                                            "value": shuffleArray(JSON.parse(JSON.stringify(item.cuts))).join('')
                                        }
                                    }

                                }
                                getMiniTitle(getData).then(res => {
                                    console.log('getReadTitleData', res)
                                    if (!res.code) {
                                        item.miniTitle = res.data?.model?.short_product_name.value
                                        setRefoConterData([...refoConterData])
                                    }

                                })
                            }}>智能生成导购短标题</Button>
                        </Space>
                    </Space>

                </div>)

            })}

            <Modal
                size="small"
                visible={addTitleAll}
                title="批量添加商品标题"
                okText=" 确定"
                cancelText=" 取消"
                bodyBottomMask
                wrapClassName={'sp-small-modal'}
                onCancel={() => {
                    setAddTitleAll(false)
                    setAddTitleAllText('')
                    // shearData.id_name_code = ''
                    // setShearData({ ...shearData })
                }
                }
                onOk={() => {
                    const getKon = addTitleAllText.split(/[\s,， ?]/).filter(item => item)
                    // if(getKon.length > 100) return message.error('最多添加100个标题')
                    if (!getKon) return message.error('请输入商品标题')
                    refoConterData.forEach((item, index) => {
                        if (getKon[index]) {
                            item.title = getKon[index]
                            item.cuts = [getKon[index]]
                        }
                    })

                    setRefoConterData([...refoConterData])
                    setAddTitleAll(false)
                    // console.log('getKon', getKon)
                }}>
                <TextArea placeholder="请输入标题(保证60字符以内，一行一个, 逗号分隔, 空格分隔)" autoSize={{ minRows: 15, maxRows: 30 }} value={addTitleAllText} onChange={(e: any) => {
                    setAddTitleAllText(e.target.value)
                }}></TextArea>
            </Modal>

        </div>
    )
}

export default forwardRef(TitleJieba)